<script lang="ts">
	export let content: string = "";
	import { createEventDispatcher, onMount, afterUpdate } from "svelte";
	import mermaid from "mermaid";
	import html2canvas from "html2canvas";
	
	const dispatch = createEventDispatcher();
	
	// 提取 ``` 包裹的代码部分
	let code = content
	  .split("```") // 按照反引号分割
	  .filter((_, index) => index % 2 !== 0) // 仅获取代码块部分
	  .map((block) => {
		// 去掉每个代码块的第一行，如果它是 "mermaid"
		const lines = block.split("\n");
		if (lines[0].trim().toLowerCase() === "mermaid") {
		  lines.shift(); // 去掉第一行
		}
		return lines.join("\n"); // 重新拼接
	  })
	  .join("\n"); // 最后把所有代码块拼接成一个字符串
  
	let container; // 右侧显示区域
	let codeWindow; // 代码区域容器
	let copyIcon = 'fa-regular fa-copy'; // 初始为复制图标
	let downloadIcon = 'fa-solid fa-download'; // 下载图标
	let isCopied = false; // 标识是否已经复制
	
	// 更新并重新渲染 Mermaid 图表
	const updateDiagram = async () => {
	  try {
		// Mermaid 渲染图表
		const { svg } = await mermaid.render("mermaid", code);
		container.innerHTML = svg; // 将生成的 SVG 添加到右侧容器中
	  } catch (err) {
		console.error("Mermaid render error:", err);
	  }
	};
	
	// 当组件挂载时调用
	onMount(() => {
	  updateDiagram();
	});
  
	// 处理代码修改时更新 Mermaid 图表
	const handleCodeChange = (event) => {
	  code = event.target.value;
	  updateDiagram();
	};
	
	// 复制代码到剪贴板
	const handleCopyClick = () => {
	  const textarea = document.createElement('textarea');
	  textarea.value = code;
	  document.body.appendChild(textarea);
	  textarea.select(); // 选择内容
	  const successful = document.execCommand('copy'); // 执行复制命令
	
	  if (successful) {
		copyIcon = 'fa-solid fa-check'; // 复制后显示勾选图标
		isCopied = true;
	
		// 恢复原始复制图标
		setTimeout(() => {
		  copyIcon = 'fa-regular fa-copy';
		  isCopied = false;
		}, 1500); // 1.5秒后恢复为复制图标
	  } else {
		console.error("复制失败");
	  }
	
	  document.body.removeChild(textarea); // 移除临时创建的textarea
	};

	// 将图表保存为图片
	const saveDiagramAsImage = async () => {
		try {
			html2canvas(container).then((canvas) => {
				canvas.toBlob((blob) => {
					const link = document.createElement("a");
					link.href = URL.createObjectURL(blob);
					link.download = "diagram.png";
					link.click();
				});
			});
		} catch (err) {
			console.error("Error rendering with html2canvas:", err);
		}
	};
  
	// 移除export let close
	const handleCloseClick = () => {
	  console.log("关闭按钮被点击");
	  dispatch("close"); // 派发 close 事件
	};
	
	// 同步代码区域和图表区域的高度
	const syncHeight = () => {
	  if (container && codeWindow) {
		const diagramHeight = container.offsetHeight;
		codeWindow.style.height = `${diagramHeight}px`; // 设置代码区域的高度与图表一致
	  }
	};
  
	// 每次图表渲染完成后更新代码区域高度
	afterUpdate(() => {
	  syncHeight();
	});
  </script>
  
  <div class="window">
	<button on:click={handleCloseClick} class="close-button">
	  <i class="fa-solid fa-xmark"></i> <!-- 使用叉号图标 -->
	</button>
  
	<div class="code-window" bind:this={codeWindow}>
	  <textarea 
		bind:value={code} 
		on:input={handleCodeChange} 
		class="code-textarea"
	  />
	  <button on:click={handleCopyClick} class="copy-button">
		<i class={copyIcon}></i>
	  </button>
	</div>
	
	<div class="diagram-window">
	  <span bind:this={container} />
	  <button on:click={saveDiagramAsImage} class="download-button">
		<i class={downloadIcon}></i>
	  </button>
	</div>
  </div>
  
  <style>
	.window {
	  display: flex;
	  justify-content: space-between;
	  padding: 20px;
	  border-radius: 8px;
	  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
	  max-width: 1000px; /* 最大宽度 */
	  margin: auto; /* 居中 */
	  position: relative;
	}
  
	.close-button {
	  position: absolute;
	  top: 2px;
	  right: 5px;
	  background-color: transparent;
	  border: none;
	  font-size: 20px;
	  cursor: pointer;
	  color: #6a4c9c; /* 紫色 */
	  width: 1%;
	}
  
	.close-button:hover {
	  color: #4a3b75; /* 深紫色 */
	  background-color: transparent;
	}
  
	.code-window {
	  width: 48%;
	  position: relative; /* 相对定位以便定位复制按钮 */
	}
  
	.code-textarea {
	  width: 100%;
	  height: 100%; /* 代码区域高度占满 */
	  padding: 10px;
	  font-family: monospace;
	  border: 1px solid #ccc;
	  background-color: #f5f5f5;
	  border-radius: 4px;
	  resize: vertical;
	  font-size: 14px;
	  color: #333;
	}
  
	.diagram-window {
	  position: relative;
	  width: 48%;
	  border: 1px solid #ddd;
	  border-radius: 4px;
	  padding: 10px;
	  background-color: #f9f9f9;
	  overflow-y: auto; /* 保证图表不会溢出 */
	}
  
	pre {
	  background-color: #f4f4f4;
	  padding: 10px;
	  border-radius: 4px;
	}
  
	/* button {
	  background-color: #007bff;
	  color: white;
	  padding: 4px 8px;
	  border: none;
	  border-radius: 4px;
	  cursor: pointer;
	  margin-top: 3px;
	} */
  
	/* button:hover {
	  background-color: #e0e0e0;
	} */
  
	.copy-button {
	  background-color: transparent;
	  position: absolute;
	  top: 10px;
	  right: 10px;
	  border: none;
	  font-size: 16px; /* 缩小图标 */
	  cursor: pointer;
	}
  
	.copy-button i {
	  font-size: 16px;
	  color: #bc81ff; /* 紫色 */
	}
  
	.copy-button:hover i {
	  color: #a65cfa;
	}

	.download-button {
	  background-color: transparent;
	  position: absolute;
	  top: 10px;
	  right: 10px;
	  border: none;
	  font-size: 16px; /* 缩小图标 */
	  cursor: pointer;
	}

	.download-button i {
	  font-size: 16px;
	  color: #bc81ff; 
	}

	.download-button:hover i {
	  color: #a65cfa;
	}
  </style>
  
  <!-- 使用 Font Awesome -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" />
  